/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bsc.war.form;

import bsc.ejb.entity.ActionPlan;
import bsc.ejb.entity.ActionPlanPerson;
import bsc.ejb.entity.Attachment;
import bsc.ejb.entity.Person;
import bsc.ejb.entity.ScoreCard;
import bsc.ejb.metadata.Colorimetry;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import bsc.war.service.FileUtils;
import bsc.war.service.ScoreCardUtils;
import java.util.Date;
import java.util.Map;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

//org.apache.commons.validator.GenericValidator
/**
 *
 * @author Miguel Angel
 */
public class NewActionPlan extends AbstractController {

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        try {
            DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");
            //Se manipula el archivo seleccionado
            Map<String, Object> parameterValues = FileUtils.getMultipartParameters(request);
            Object file = parameterValues.get("file");
            byte[] attachmentFile = file == null || !(file instanceof byte[]) ? null : (byte[]) file;
            String attachmentFileName = (String) parameterValues.get("file_filename");

            //Se obtiene el scorecard

            String idScoreCard = (String) parameterValues.get("scoreCard");
            ScoreCard scoreCard = delegate.findScoreCard(Long.parseLong(idScoreCard));

            //se obtiene al author

            HttpSession session = request.getSession();
            Person author = (Person) session.getAttribute("person");

            //Se obtiene el responsable
            String idPersonResponsible = (String) parameterValues.get("responsible");
            Person responsible = delegate.findPerson(Long.parseLong(idPersonResponsible));

            //Se comienza a crear el ActionPlan
            ActionPlan actionPlan = (ActionPlan) Factory.getBean("ActionPlan");

            actionPlan.setTitle((String) parameterValues.get("title"));
            actionPlan.setDescription((String) parameterValues.get("description"));

            //Se toman las fechas

            Date initialDate = null;
            Date endDate = null;

            Integer tmpDate[] = new Integer[3];
            StringTokenizer dateTokens = new StringTokenizer((String) parameterValues.get("actionPlanInitialDate"), "/");
            for (int i = 0; i < 3; i++) {
                tmpDate[i] = Integer.parseInt(dateTokens.nextToken());
            }

            Integer tmpDateFinal[] = new Integer[3];
            StringTokenizer dateTokensFinal = new StringTokenizer((String) parameterValues.get("actionPlanEndDate"), "/");
            for (int i = 0; i < 3; i++) {
                tmpDateFinal[i] = Integer.parseInt(dateTokensFinal.nextToken());
            }

            initialDate = ScoreCardUtils.generateDate(tmpDate[0], tmpDate[1], tmpDate[2]);
            endDate = ScoreCardUtils.generateDate(tmpDateFinal[0], tmpDateFinal[1], tmpDateFinal[2]);

            actionPlan.setActionPlanInitialDate(initialDate);
            actionPlan.setActionPlanEndDate(endDate);

            //Status
            actionPlan.setStatus(ActionPlan.Status.valueOf((String)parameterValues.get("status")));

            //Colorimetry
            String colorimetryString= (String)parameterValues.get("colorimetry");
            Long idColorimetry = Long.parseLong(colorimetryString);
            Colorimetry colorimetry = delegate.findColorimetry(idColorimetry);
            actionPlan.setColorimetry(colorimetry);

            //ScoreCard
            actionPlan.setScoreCard(scoreCard);

            
            //Se crea el actionPlan
            delegate.createActionPlan(actionPlan);


            if (attachmentFile != null && attachmentFile.length > 0) {

                Attachment attachment = (Attachment) Factory.getBean("Attachment");
                attachment.setActionPlan(actionPlan);
                delegate.createAttachment(attachment);

                String fileName = FileUtils.generateFilename(attachment, FileUtils.FileType.ATTACHMENT) + "_" + attachmentFileName;
                boolean fileSaved = FileUtils.saveFile(attachmentFile, fileName, FileUtils.FileType.ATTACHMENT);
                if (!fileSaved) {
                    delegate.deleteAttachment(attachment);
                } else {
                    attachment.setFilename(fileName);
                    attachment.setAttachment(FileUtils.generateFileURL(fileName, FileUtils.FileType.ATTACHMENT));
                    delegate.updateAttachment(attachment);
                }
            }

            //Se crean los actionPlanPersons - Author
            ActionPlanPerson actionPlanPersonAuthor = (ActionPlanPerson) Factory.getBean("ActionPlanPerson");
            actionPlanPersonAuthor.setActionPlan(actionPlan);
            actionPlanPersonAuthor.setPerson(author);
            actionPlanPersonAuthor.setProfile(ActionPlanPerson.Profile.AUTHOR);
            delegate.createActionPlanPerson(actionPlanPersonAuthor);

            //Se crean los actionPlanPersons - Responsible
            ActionPlanPerson actionPlanPersonResponsible = (ActionPlanPerson) Factory.getBean("ActionPlanPerson");
            actionPlanPersonResponsible.setActionPlan(actionPlan);
            actionPlanPersonResponsible.setPerson(responsible);
            actionPlanPersonResponsible.setProfile(ActionPlanPerson.Profile.RESPONSIBLE);
            delegate.createActionPlanPerson(actionPlanPersonResponsible);

            

        } catch (Exception e) {
            e.printStackTrace();
        }

        return new ModelAndView("newActionPlan");
    }
}
